import React from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Button, Modal } from 'antd';
import { WeaSwitch, WeaTableNew } from 'comsMobx';
import {
	WeaLocaleProvider,
    WeaTop,
    WeaTab,
    WeaSearchGroup,
    WeaRightMenu,
    WeaDialog,
    WeaFormItem,
    WeaProgress,
    WeaTools,
} from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

const WeaTable = WeaTableNew.WeaTable;

// 渲染优化 单独提出的组件
class WeaProgressCom extends React.PureComponent {
  shouldComponentUpdate(nextProps, nextState, nextContext) {
    if (nextProps.percent !== undefined && nextProps.percent === this.props.percent) {
      return false
    }
    return  true
  }

  render() {
    return(
      <WeaProgress strokeColor="#89cdee" {...this.props}/>
    )
  }
}

@inject('SpaceStore')
@observer
class Space extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        		showModal: false,
        		type: 0,
    		};
        ['getOperatesClick', 'hideMoudle', 'hideMoudle', 'saveMoudle', 'onRightMenuClick', 'batchSet'].forEach(i => {
          this[i] = this[i].bind(this)
        })
    }
    componentDidMount() { // 一些初始化请求
        const { SpaceStore } = this.props;
        // 初始化列表
        SpaceStore.doLoading();
    }
    componentWillReceiveProps(nextProps) {
    }

    componentWillUnmount() {
        // 组件卸载时一般清理一些状态
    }

    render() {
    	const { SpaceStore } = this.props;
    	const { sessionkey, loading, tableStore } = SpaceStore;
    	const { showModal, type } = this.state;
        const footer = [
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@w2mv6b@footer_backBtn`} key="back" type="ghost" onClick={this.hideMoudle}>{getLabel(1290, '返 回')}</Button>,
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@2u1cby@footer_saveBtn`} key="submit" type="primary" onClick={this.saveMoudle}>
              {getLabel(86, '保 存')}
              </Button>];
        return (
            <div className="album-space">
                        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@3aqnep`} datas={this.getRightMenu()} onClick={this.onRightMenuClick}>
                            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@8fslw0`}
                              title={getLabel(20290, '相册空间')}
                              loading={loading}
                              icon={<i className="icon-coms-photo" />}
                              iconBgcolor="#1a57a0"
                              buttons={this.getButtons()}
                              buttonSpace={10}
                              showDropIcon={true}
                              dropMenuDatas={this.getRightMenu()}
                              onDropMenuClick={this.onRightMenuClick}
                            >
	                            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@ov2n2q`}
                                searchType={['base', '']}
                                onSearch={(v) => { SpaceStore.doLoading({ flowTitle: v }); }}
	                            />
	                            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@9dodr4`}
                                loading={loading}
                                comsWeaTableStore={tableStore}
                                getColumns={this.reRenderColumns}
                                hasOrder={true}
                                needScroll={false}
                                onOperatesClick={this.getOperatesClick}
                                sessionkey={sessionkey}
	                            />
                            </WeaTop>

	                        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@nor4ri`}
                            title={type == '0' ? getLabel(84058, '批量设置相册空间') : getLabel(84057, '编辑相册空间')}
                            visible={showModal}
                            buttons={footer}
                            icon="icon-coms-photo"
                            iconBgcolor="#1a57a0"
                            onCancel={this.hideMoudle}
                            style={{ width: 500, height: 300 }}
	                        >
	                        {this.getNewOrEditFields()}
	                        </WeaDialog>
                        </WeaRightMenu>
            </div>
        );
    }

    reRenderColumns = (columns) => {
        columns.forEach((c) => {
            if (c.dataIndex == 'rate') {
                c.render = function (text, record) {
                	if (record._stat) {
                		return '';
                	}
                		let rate1 = 0;
                    	if (record.rate) {
                    		rate1 = record.rate;
                    	}
                        return (<span className="wea-prj-progressStyle" >
                          <WeaProgressCom ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@uihtuz@${record.id}`} percent={rate1} />
                        </span>);
                };
            }
        });
        return columns;
    }

  // 用于渲染编辑或新建模板的表单
    getNewOrEditFields() {
        const { SpaceStore } = this.props;
        let conditioninfo = SpaceStore.conditioninfo;
        conditioninfo = toJS(conditioninfo);
        const { form } = SpaceStore;
        const { isFormInit } = form;
        let group = [];
        isFormInit && conditioninfo.map((c) => {
        	let items = [];
            c.items.map((fields) => {
              items.push({
                com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@jiop5m@${(fields.domkey && fields.domkey[0]) ? fields.domkey[0] : 'jiop5m'}`}
                  label={`${fields.label}`}
                  labelCol={{ span: `${fields.labelcol}` }}
                  wrapperCol={{ span: `${fields.fieldcol}` }}
                >
                          <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@2co7w7@${(fields.domkey && fields.domkey[0]) ? fields.domkey[0] : '2co7w7'}`} fieldConfig={fields} form={form} />
                    </WeaFormItem>),
                colSpan: 1,
                hide: fields.domkey == 'subid',
              });
            });
            group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@l860ex@newOrEditFields_WeaSearchGroup`} col={1} needTigger={false} showGroup={true} items={items} />);
          });
        return group;
	}

    // 右键菜单事件绑定
    onRightMenuClick(key) {
        const { SpaceStore } = this.props;
        const { currentuserid } = SpaceStore;
        if (key == '0') {
        	if (currentuserid == 1) {
        		this.batchSet();
        	}
        }
    }

    // 右键菜单
    getRightMenu() {
    	const { SpaceStore } = this.props;
    	const { currentuserid } = SpaceStore;
        let btns = [];
        let disabled1 = true;
        if (currentuserid == 1) {
        	disabled1 = false;
        }
        btns.push({
            icon: <i className="icon-coms-edit" />,
            content: getLabel(33511, '批量设置'),
            disabled: disabled1,
        });
        return btns;
    }

    // 顶部右侧菜单
    getButtons() {
    	const { SpaceStore } = this.props;
    	const { currentuserid } = SpaceStore;
    	let btns = [];
    	if (currentuserid == 1) {
    		btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@uxnfj0@getButtons_batchSetBtn`} type="primary" onClick={this.batchSet}>{getLabel(33511, '批量设置')}</Button>);
    	}
        return btns;
    }

    // 批量编辑
    batchSet() {
    	const { SpaceStore } = this.props;
 	   	const { showModal, type } = this.state;
 	   	SpaceStore.initBatchForm();
 	   	this.setState({ showModal: true, type: 0 });
    }

    // 分页组件操作菜单
    getOperatesClick(record, index, operate, flag) {
    	const { SpaceStore } = this.props;
        if (flag == 0) {
        	SpaceStore.initSingleSetForm({ subid: record.id });
        	this.setState({ showModal: true, type: 1 });
        }
    }

    hideMoudle() {
    	const { SpaceStore } = this.props;
	    const { form } = SpaceStore;

	    SpaceStore.form.reset();
		this.setState({ showModal: false, type: 0 });
    }

    saveMoudle() {
	    const { SpaceStore } = this.props;
	    const { form } = SpaceStore;
	    form.validate().then((f) => {
            if (f.isValid) {
        		SpaceStore.saveOrUpdateSpace(form.getFormParams());
        		SpaceStore.form.reset();
        		this.setState({ showModal: false, type: 0 });
            } else {
                f.showErrors();
                   Modal.warning({
                    title: getLabel(15172, '系统提示'),
                    content: getLabel(383975, '必要信息不完整，红色标记为必填项！'),
                });
            }
        });
	}
}

// 组件检错机制
class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== '';
        return (
            <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@t3ziru`} msg={hasErrorMsg ? this.props.error : getLabel(384697, '对不起，该页面异常，请联系管理员！')} />
        );
    }
}

Space = WeaTools.tryCatch(React, MyErrorHandler, { error: '' })(Space);

export default Space;
